#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
script name: seed
Created on 2020/2/11 22:19 by PyCharm
@author: fujianjian
"""
import json
import logging
from datetime import datetime

import requests
from sqlalchemy import Column, Integer, String, TIMESTAMP, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()


class Seed(Base):
    """
    种子模型
    """
    __tablename__ = 't_seed'
    id = Column(Integer, primary_key=True, autoincrement=True, comment='主键')
    name = Column(String(127), nullable=False, comment='名称')
    size = Column(String(21), comment='种子大小')
    hot = Column(Integer, comment='人气')
    magnet = Column(String(127), nullable=False, comment='magnet')
    pub_time = Column(TIMESTAMP, comment='发布时间')
    search_channel = Column(String(16), comment='获取渠道')
    status = Column(String(8), default='VALID', comment='状态')

    product_id = Column(Integer, nullable=False, comment='作品Id')

    created_time = Column(TIMESTAMP, comment='创建时间')
    updated_time = Column(TIMESTAMP, comment='更新时间')


class Product(Base):
    """
    作品
    """
    __tablename__ = 't_product'
    id = Column(Integer, primary_key=True, autoincrement=True, comment='组件')
    name = Column(String(127), nullable=False, index=True, comment='作品名称')
    last_search = Column(TIMESTAMP, nullable=False, comment='上次查询时间',
                         default=datetime.now())
    seed_count = Column(Integer, nullable=False, default=0, comment='种子数量')
    created_time = Column(TIMESTAMP, name='created_time', nullable=True,
                          comment='创建时间', default=datetime.now())
    updated_time = Column(TIMESTAMP, name='updated_time', nullable=True,
                          comment='更新时间', default=datetime.now())


class Ostrich:
    __ostrich_url = 'https://www.tnbt1.xyz/api/search'

    def __init__(self) -> None:
        super().__init__()

    def req_seed(self, product_name=''):
        """
        请求作品的下载种子
        :param product_name:
        :return:
        """
        logging.info('req seed for product name: %s', product_name)
        if product_name:
            keyword = {'source': '种子搜', 'keyword': product_name, 'page': '1', 'sort': 'time'}
            try:
                res = requests.get(self.__ostrich_url, params=keyword)
                logging.info('search by ostrich res: %s' % res.text)
                res_json = json.loads(res.text, encoding='utf-8')
                results = res_json['data']['results']

                seed_list = [Seed(name=ret['name'], size=ret['formatSize'],
                                  magnet=ret['magnet'], hot=ret['hot'],
                                  pub_time=datetime.strptime(ret['date'], '%Y-%m-%d'),
                                  search_channel='ostrich', status='VALID',
                                  created_time=datetime.now(),
                                  updated_time=datetime.now()) for ret in results]
                return seed_list

            except Exception as e:
                logging.info('search by ostrich failed, please check net is work')
                logging.error('ostrich error: %s' % e)


class HandleSeed(object):
    # __db_connection_str = 'mysql+mysqlconnector://root:root@localhost:33006/mansite'
    __db_connection_str = 'mysql+pymysql://root:root@localhost:33006/mansite'

    logging.basicConfig(level=logging.INFO, format='%(asctime)s :: %(pathname)s :: %(lineno)s :: %(message)s')

    def __init__(self) -> None:
        super().__init__()

        # 初始化数据库连接
        engine = create_engine(self.__db_connection_str, encoding='utf-8', echo=True, max_overflow=5)
        # 初始化数据库表结构
        Base.metadata.create_all(bind=engine)
        # 创建DBSession类型
        self.DBSession = sessionmaker(bind=engine)

    def find_seed(self, product_name='', force=False):
        logging.info('find seed %s' % product_name)
        if product_name:
            session = self.DBSession()
            p_list = session.query(Product).filter(Product.name == product_name).all()
            # search_tool = SearchSeed()
            if force:
                for p in p_list:
                    session.delete(Seed(product_id=p.id))
                    session.delete(p)
                session.commit()
            else:
                if p_list:
                    logging.info('the product seed is exits not search')
                    return
                # elif not search_tool.channel_list:
                #     logging.info('not have search tools, please implement a tool first')
                #     return
                else:
                    p = Product(name=product_name, created_time=datetime.now(), updated_time=datetime.now())
                    session.add(p)
                    # 获取自增长的Id值
                    session.flush()

                    # for channel in search_tool.channel_list:
                    channel = Ostrich()
                    seed_list = channel.req_seed(product_name)
                    # 有一个通道查询到结果就返回
                    if seed_list:
                        p.seed_count = len(seed_list)
                        p.updated_time = datetime.now()
                        for seed in seed_list:
                            seed.product_id = p.id
                        session.add_all(seed_list)
                        session.commit()
            session.close()


if __name__ == '__main__':
    hs = HandleSeed()
    hs.find_seed('肖生克的救赎')
